# encoding: utf-8
from app import create_app
import sys

from app.extensions import db
from app.modules.common.utils import DbCommit
from app.modules.role.models import Role, RoleMenu

application = create_app(flask_config = 'testing')
from app.modules.user.models import User

reload(sys)
sys.setdefaultencoding('utf8')


def delRole(roleName):
    with application.app_context():
        _role = Role.query.filter_by(role_name = roleName).first()
        if _role is None:
            print "%s 不存在" % roleName
            return
        _list = User.query.all()
        for _user in _list:
            if '|%s|' % _role.role_id not in _user.role:
                continue
            _user.role = str(_user.role).replace('|%s|' % _role.role_id, '|')
        for _menu in RoleMenu.query.filter_by(role_id = _role.role_id).all():
            db.session.delete(_menu)
        db.session.delete(_role)
        DbCommit()
        pass


def updateRole(oldName, newName, desc):
    with application.app_context():
        _role = Role.query.filter_by(role_name = oldName).first()
        if _role is None:
            print "%s 不存在" % oldName
            return
        _role.role_name = newName
        _role.desc = desc
        print _role
        DbCommit()
        pass


def addRole():
    with application.app_context():
        _roleYF = Role("yf", "研发中心")
        _rolePT = Role("pt", "普通用户")
        db.session.add(_roleYF)
        db.session.add(_rolePT)
        db.session.flush()
        _dev = Role.query.filter_by(role_name = "dev").first()
        _qa = Role.query.filter_by(role_name = "qa").first()
        _ops = Role.query.filter_by(role_name = "ops").first()
        _pdm = Role.query.filter_by(role_name = "pdm").first()

        _list = User.query.all()
        for _user in _list:
            if '|%s|' % _dev.role_id in _user.role \
                    or '|%s|' % _qa.role_id in _user.role \
                    or '|%s|' % _ops.role_id in _user.role \
                    or '|%s|' % _pdm.role_id in _user.role:

                _user.role = "%s%s|" % (_user.role, _roleYF.role_id)
            else:
                _user.role = "%s%s|" % (_user.role, _rolePT.role_id)
        DbCommit()
        pass


delRole("pd")
delRole("matrix")

updateRole("need_master", "dept_charger", "部门负责人")

addRole()
